/**
 * 爬虫：书籍信息
 * 当前来源为“豆瓣”
 * 
 */

const express = require("express");
const axios = require('axios').default;
const cheerio = require('cheerio');

const config = require('../config');
const common = require('../util/common');

module.exports = {
    fetch
};


let bookInfo = {
    title: '',
    pic: '',
    author: '',
    publisher: '',
    translator: '',
    pubdate: '',
    pages: '',
    price: '',
    binding: '',
    series: '',
    isbn: '',
};

/**
 * 
 * @param {express.Request} req 
 * @param {express.Response} res 
 * @param {express.NextFunction} next 
 */
function fetch(req, res, next) {
    clearBookInfo();
    const url = config.douban.bookUrl + req.params.isbn;
    axios.get(url).then(function (response) {
        let bookInfo = fetchDouban(response.data);
        res.json(common.getReturnJSONData(200, '豆瓣书籍信息', bookInfo));
    }).catch(function (error) {
        console.error(error);
        res.json(common.getReturnJSONData(400, '无法获取信息'));
    });
}

/**
 * 通过分析对应豆瓣页面获得指定书籍信息
 * @param {String} html 
 * @returns {bookInfo}
 */
function fetchDouban(html) {
    clearBookInfo();
    const $ = cheerio.load(html);
    bookInfo.title = $(config.douban.bookTitle).text();
    bookInfo.pic = $(config.douban.bookPic).attr('src');
    let info = $(config.douban.bookInfo).text().trim().split('\n');
    // console.log(info);

    formatInfo(bookInfo, info);

    // console.log(bookInfo);

    return bookInfo;
};


/**
 * 豆瓣网页信息中作者与译者信息与其他信息的标签不同，从问问方式处理
 * @param {bookInfo} bookInfo 
 * @param {String[]} info 
 */
function formatInfo(bookInfo, info) {

    let infoArr = [];


    info.forEach(element => {
        element = element.trim();
        if (!element.match(/^[ ]*$/)) {
            infoArr.push(element);
        }
    });



    let infoStr = infoArr.join('');

    console.log(infoStr);

    let temp = infoStr.replace('作者:', '作者:')
        .replace('出版社:', '|出版社:')
        .replace('原作名:', '|原作名:')
        .replace('译者:', '|译者:')
        .replace('出版年:', '|出版年:')
        .replace('页数:', '|页数:')
        .replace('定价:', '|定价:')
        .replace('装帧:', '|装帧:')
        .replace('丛书:', '|丛书:')
        .replace('ISBN:', '|ISBN:');
    console.log(temp);

    // let temp = '';
    // let start = 0;
    // for (let i = start; i < infoArr.length; i++) {
    //     if (infoArr[i].match('作者')) {
    //         temp += infoArr[i];
    //     } else if (infoArr[i].match('出版社')) {
    //         infoC.push(temp);
    //         start = i;
    //         temp = '';
    //         break;
    //     }else{
    //         temp += infoArr[i];
    //     }
    // }
    // for (let i = start; i < infoArr.length; i++) {
    //     if (!infoArr[i].match('译者')) {
    //         infoC.push(infoArr[i]);
    //     } else {
    //         start = i;
    //         break;
    //     }
    // }
    // for (let i = start; i < infoArr.length; i++) {
    //     if (infoArr[i].match('译者')) {
    //         temp += infoArr[i];
    //     } else if (infoArr[i].match('出版年')) {
    //         infoC.push(temp);
    //         start = i;
    //         temp = '';
    //         break;
    //     }else{
    //         temp += infoArr[i];
    //     }
    // }
    // for (let i = start; i < infoArr.length; i++) {
    //     infoC.push(infoArr[i]);
    // }

    // console.log(infoC);
    let infoC = temp.split('|');    

    for (let i = 0; i < infoC.length; i++) {
        const element = infoC[i];
        if (element.match('作者')) {
            bookInfo.author = element.split(':')[1].trim();
        }
        if (element.match('出版社')) {
            bookInfo.publisher = element.split(':')[1].trim();
        }
        if (element.match('译者')) {
            bookInfo.translator = element.split(':')[1].trim();
        }
        if (element.match('出版年')) {
            bookInfo.pubdate = element.split(':')[1].trim();
        }
        if (element.match('页数')) {
            bookInfo.pages = element.split(':')[1].trim();
        }
        if (element.match('定价')) {
            bookInfo.price = element.split(':')[1].trim();
        }
        if (element.match('装帧')) {
            bookInfo.binding = element.split(':')[1].trim();
        }
        if (element.match('丛书')) {
            bookInfo.series = element.split(':')[1].trim();
        }
        if (element.match('ISBN')) {
            bookInfo.isbn = element.split(':')[1].trim();
        }
    }
}

/**
 * 清除bookInfo原有内容
 */
function clearBookInfo() {
    for (const key in bookInfo) {
        if (Object.hasOwnProperty.call(bookInfo, key)) {
            bookInfo[key] = '';
        }
    }
}